import json

from flask import jsonify, request
from flask_login import current_user

from app.libs.helper import is_isbn_or_key
from app.spider.yushu_book import YuShuBook
from app.forms.book import SearchForm

from . import web
from ..models.gift import Gift
from ..models.wish import Wish
from ..view_models.book import BookViewModel, BookCollection
from ..view_models.trade import TradeInfo


@web.route('/book/search')
def search():
    """
    :param q: 普通关键字 isbn
    :param page:
    :return:
    """
    # 验证层
    form = SearchForm(request.args)

    books = BookCollection()

    if form.validate():
        q = form.q.data.strip()
        page = form.page.data
        isbn_or_key = is_isbn_or_key(q)
        yushu_book = YuShuBook()

        if isbn_or_key == 'isbn':
            yushu_book.search_by_isbn(q)
        else:
            yushu_book.search_by_keyword(q, page)

        books.fill(yushu_book, q)
        return json.dumps(books, default=lambda o: o.__dict__)
        # return jsonify(books)
    else:
        return jsonify(form.errors)

@web.route('/book/<isbn>/detail')
def book_detail(isbn):
    has_in_gifts = False
    has_in_wishes = False

    yushu_book = YuShuBook()
    yushu_book.search_by_isbn(isbn)
    book = BookViewModel(yushu_book.first)
    if current_user.is_authenticated:
        if Gift.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_gifts = True
        if Wish.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            has_in_wishes = True

    trade_gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    trade_wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()

    trade_wisher_model = TradeInfo(trade_wishes)
    trade_gifts_model = TradeInfo(trade_gifts)

    return json.dumps({
        'book': book,
        'trade_wisher_model': trade_wisher_model,
        'trade_gifts_model': trade_gifts_model,
        'has_in_gifts': has_in_gifts,
        'has_in_wishes': has_in_wishes
    }, default=lambda o:o.__dict__)

    # return json.dumps(result), 200, { 'content-type': 'application/json' }
